﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SharedLib.BasicServices.MessageFramework;
using Tracy.DataModel;
using Tracy;
using System.IO;
using System.ComponentModel;
using SharedLib.Helpers;

namespace TracyGUI
{
    public partial class FormMain
    {
        private Dictionary<string, ListViewItem> _mappingMediaFile = new Dictionary<string, ListViewItem>();

        private void AddMediaFilesToUI(List<MediaFile> files)
        {
            if (files != null)
            {
                foreach (MediaFile file in files)
                {
                    if (file.Visible == "true")
                    {
                        AddItemToMediaFileListView(file);
                    }
                }
            }
        }

        private void OnResourceMediaFilesAssigned(IAppMessage msg)
        {
            
            Resource res = msg.Data as Resource;
            List<MediaFile> files = msg.Result as List<MediaFile>;
            if (files != null && files.Count > 0)
            {
                if (listBoxEntries.SelectedIndex != -1 && listBoxEntries.SelectedItem is TracyGUI.UIData.ListBoxItemEntry)
                {
                    TracyGUI.UIData.ListBoxItemEntry selectedItem = listBoxEntries.SelectedItem as TracyGUI.UIData.ListBoxItemEntry;
                    if (selectedItem.Data != null)
                    {
                        if (selectedItem.Data.ID != res.Entry.ID) return;
                    }
                }
                AddMediaFilesToUI(files);
            }
            //TODO: update entry (new item count)
        }

        private void ClearMediaFileListView()
        {
            listViewMediaFile.Items.Clear();
            _mappingMediaFile.Clear();
        }
        private void AddItemToMediaFileListView(MediaFile file)
        {
            ListViewItem lvItemMediaFile = new ListViewItem();
            lvItemMediaFile.Name = "Name";
            lvItemMediaFile.Tag = file;
            lvItemMediaFile.Text = file.FileName;

            AddSubListViewItem(lvItemMediaFile, "Status", file.Status);
            listViewMediaFile.Items.Insert(0, lvItemMediaFile);
            _mappingMediaFile.Add(file.ID, lvItemMediaFile);
        }

        private void LoadMediaFiles()
        {
            ClearMediaFileListView();
            AddMediaFilesToUI(TracyBus.Instance.MediaFileProvider.GetItems());
        }

        private void ChangeMediaFileStatus(MediaFile file, string newStatus)
        {
            if (file != null)
            {
                file.Status = newStatus;
                TracyBus.Instance.MediaFileProvider.UpdateItem(file);
                if (file.Visible == "true")
                {
                    if (_mappingMediaFile.ContainsKey(file.ID))
                    {
                        ListViewItem lvItemMediaFile = _mappingMediaFile[file.ID];
                        lvItemMediaFile.Tag = file;
                        lvItemMediaFile.SubItems["Status"].Text = newStatus;
                    }
                    UpdateEntry(file.Resource.Entry);
                }
            }
        }

        private void listViewMediaFile_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (listViewMediaFile.SelectedItems.Count > 0)
            {
                //Open the first item
                MediaFile file = listViewMediaFile.SelectedItems[0].Tag as MediaFile;
                //TODO: Open with...
                //TODO: Embeded player
                if (file.Status == "Ready" || file.Status == "Watched")
                {
                    string filePath = file.GetSavedFilePath();
                    if (filePath != null && File.Exists(filePath))
                    {
                        System.Diagnostics.Process.Start(filePath);
                        if (file.Status != "Watched") ChangeMediaFileStatus(file, "Watched");
                    }
                    else
                    {
                        MessageBox.Show("File not found: " + filePath);
                        file.Properties[MediaFile.KEY_PREVIOUS_STATUS] = file.Status;
                        file.Status = "Missing";
                        TracyBus.Instance.MediaFileProvider.UpdateItem(file);
                    }
                }
                
            }
        }


        private void openContainingFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listViewMediaFile.SelectedItems.Count > 0)
            {
                //Open the first item
                MediaFile file = listViewMediaFile.SelectedItems[0].Tag as MediaFile;
                System.Diagnostics.Process.Start(Path.GetDirectoryName(file.GetSavedFilePath()));
            }
            
        }

        private void contextMenuStripFile_Opening(object sender, CancelEventArgs e)
        {
            if (listViewMediaFile.SelectedItems.Count == 0)
            {
                changeStatusToolStripMenuItem.Enabled = false;
            }
            else
            {
                changeStatusToolStripMenuItem.Enabled = true;
            }
        }

        private void changeToWatchedStatusToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvItem in listViewMediaFile.SelectedItems)
            {
                MediaFile file = lvItem.Tag as MediaFile;
                ChangeMediaFileStatus(file, "Watched");
            }
        }

        private void changeToReadyStatusToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvItem in listViewMediaFile.SelectedItems)
            {
                MediaFile file = lvItem.Tag as MediaFile;
                ChangeMediaFileStatus(file, "Ready");
            }
        }

        private void removeFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<MediaFile> filesToRemove = new List<MediaFile>();
            
            
            //Prepare Data and remove ui item
            foreach (ListViewItem item in listViewMediaFile.SelectedItems)
            {
                MediaFile file = item.Tag as MediaFile;
                filesToRemove.Add(file);
                listViewMediaFile.Items.Remove(item);
            }

            RemoveMediaFiles(filesToRemove);
        }

        private void RemoveMediaFiles(List<MediaFile> filesToRemove)
        {
            List<string> physicalFilesToDelete = new List<string>();
            List<Entry> entriesToUpdate = new List<Entry>();
            StringWriter sw = new StringWriter();
            sw.Write("Do you want to remove the physical file(s) as well?");
            //Remove data
            foreach (MediaFile file in filesToRemove)
            {
                _mappingMediaFile.Remove(file.ID);
                if (file.Status == "Ready" || file.Status == "Watched")
                {
                    physicalFilesToDelete.Add(file.GetSavedFilePath());
                    sw.Write("\r\n" + file.FileName);
                    if (file.Resource != null && file.Resource.Entry != null && !entriesToUpdate.Contains(file.Resource.Entry))
                    {
                        entriesToUpdate.Add(file.Resource.Entry);
                    }
                }
                TracyBus.Instance.MediaFileProvider.RemoveItem(file.ID);
            }

            //Update entry
            foreach (Entry entry in entriesToUpdate)
            {
                UpdateEntry(entry);
            }

            //Delete physical file
            if (physicalFilesToDelete.Count > 0)
            {
                if (MessageBox.Show(sw.ToString(), "Delete File", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    List<string> folders = new List<string>();
                    foreach (string filePath in physicalFilesToDelete)
                    {
                        if (filePath != null)
                        {
                            string path = Path.GetDirectoryName(filePath);
                            if (path != null && !folders.Contains(path))
                            {
                                folders.Add(path);
                            }
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                    }

                    //Remove empty folders
                    foreach (string folder in folders)
                    {
                        IOHelper.DeleteFolderIfNotEmpty(folder);
                    }
                }
            }
        }
    }
}
